Python Code For The "Try It" Tab

The code ask the user for an image. Which will be read by our python file, and server will be detecting the face using the OpenCV and Dlib library. then it will be placing the Golden ratio spiral on the detected face using the PIL library.

So, lets breakdown the code and understand how it's done.

First, we are importing the library that we will be using throughout the code.

In [1]:
import cv2
import dlib
from PIL import Image, ImageDraw, ImageFilter

Now, lets use them to read the image file first,
Since detection works only on grayscale images. So it is important to convert the color image to grayscale.(3rd line)
then we will identify where is the face in the image using Dlib function called get_frontal_face_detector().
Now, we can retrive the coordinates of the face detected (for loop)

And finally form a rectangle using those coordinates

In [2]:
img = cv2.imread("hero.jpg")

gray = cv2.cvtColor(src=img, code=cv2.COLOR_BGR2GRAY)

detector = dlib.get_frontal_face_detector()

faces = detector(gray)
for face in faces:
    x1 = face.left()
    y1 = face.top() 
    x2 = face.right()
    y2 = face.bottom() 
    
    rect = cv2.rectangle(img=img, pt1=(x1, y1), pt2=(x2, y2), color=(500, 0, 100), thickness=4)

Here's, how the output turns to be,

detected_face.PNG

Getting the coordinates of rectangle

In [3]:
detected_faces = dlib.rectangle(x1,y1,x2,y2)
print(detected_faces)
[(1229, 238) (1601, 610)]

And, now placing the spiral over the image using the PIL library

In [4]:
background = Image.open("hero.jpg")
foreground = Image.open("spiral1.png")

background.paste(foreground, (x1,y1), foreground)
background.show()

finalOutput.PNG